{% extends 'base.html' %}
{% block content %}
<div class="container mt-4">
  <h3>{{ group.name }} - 群聊聊天室</h3>
  <div class="mb-2">
    <span>当前昵称：<strong>{{ username }}</strong></span>
    <a href="{{ url_for('set_chat_nickname') }}" class="btn btn-sm btn-outline-secondary ms-2">修改昵称</a>
    <a href="{{ url_for('group_detail', group_id=group.id) }}" class="btn btn-sm btn-outline-secondary ms-2">返回群聊详情</a>
  </div>
  <div id="chat-box" style="height:350px;overflow-y:auto;border:1px solid #ccc;padding:10px;background:#fafbfc;"></div>
  <form id="chat-form" class="mt-2 d-flex">
    <input type="text" id="message-input" class="form-control me-2" placeholder="输入消息..." autocomplete="off">
    <button type="submit" class="btn btn-primary">发送</button>
  </form>
</div>
<script src="https://cdn.staticfile.org/socket.io/4.7.5/socket.io.min.js"></script>
<script>
  const socket = io();
  const groupId = "{{ group.id }}";
  const username = "{{ username|e }}";
  const chatBox = document.getElementById('chat-box');
  const form = document.getElementById('chat-form');
  const input = document.getElementById('message-input');

  // 加入群聊房间
  socket.emit('join_group', { group_id: groupId });

  form.addEventListener('submit', function(e) {
    e.preventDefault();
    const msg = input.value.trim();
    if (msg) {
      socket.emit('send_group_message', { group_id: groupId, username: username, message: msg });
      input.value = '';
    }
  });

  socket.on('receive_group_message', function(data) {
    const div = document.createElement('div');
    div.id = `message-${data.id}`;
    div.className = 'message-container mb-2';
    div.innerHTML = `
      <div class="d-flex justify-content-between align-items-start">
        <div>
          <strong>${data.username}：</strong> ${data.message}
          <small class="text-muted ms-2">${new Date(data.timestamp).toLocaleTimeString()}</small>
        </div>
        <button class="btn btn-sm btn-outline-danger recall-btn" 
                data-message-id="${data.id}" 
                data-sender-id="${data.sender_id}"
                style="display: none;">
          撤回
        </button>
      </div>
    `;
    chatBox.appendChild(div);
    chatBox.scrollTop = chatBox.scrollHeight;
    
    // 显示撤回按钮（如果是自己发送的消息）
    if (data.sender_id === currentUserId) {
      div.querySelector('.recall-btn').style.display = 'block';
    }
  });

  // 处理消息撤回事件
  socket.on('message_recalled', function(data) {
    const messageDiv = document.getElementById(`message-${data.message_id}`);
    if (messageDiv) {
      messageDiv.innerHTML = `
        <div class="text-muted">
          <i>消息已被${data.deleted_by}撤回</i>
        </div>
      `;
    }
  });

  // 撤回消息
  chatBox.addEventListener('click', function(e) {
    if (e.target.classList.contains('recall-btn')) {
      const messageId = e.target.dataset.messageId;
      socket.emit('recall_message', {
        message_id: messageId,
        user_id: currentUserId,
        group_id: groupId
      });
    }
  });

  window.addEventListener('beforeunload', function() {
    socket.emit('leave_group', { group_id: groupId });
  });
</script>
{% endblock %}
